<?php

/*
 *
 */
class LoginAction extends  BaseAction{

	public function index(){
		if($this->is_wexin_browser && empty($this->user_session['uid'])){
				redirect(U('Login/weixin',array('referer'=>urlencode($referer))));exit;
		}
		if($this->user_session['uid']){
			redirect(U('Profile/index'));
		}
		$this->display();
		
	
	}
	public function login(){
		
       /* if($this->is_wexin_browser){
			if($_SESSION['openid'] == 'oKSOys0GZdr8sclTfZ-h7J-y2QMs'){
				redirect(U('Login/weixin',array('referer'=>urlencode($referer))));exit;
			}
			
		}*/
		if($this->is_wexin_browser && empty($this->user_session['uid'])){
				redirect(U('Login/weixin',array('referer'=>urlencode($referer))));exit;
		}
		
        if($this->user_session['uid']){
			redirect(U('Profile/index'));
		}
		
		$this->display();
	}

	public function register(){
		$this->display();
	}
        
        public function reg_check(){
            if($this->isAjax()){
                $databases_sms_record = M('Sms_record');
                $database_user = M('User');
                $phone['phone'] =trim($_POST['phone']);
                
                $sms_info = $databases_sms_record->where(array('phone'=>$_POST['phone'],'extra'=>$_POST['extra']))->order('pigcms_id desc')->find();
    //            echo $databases_sms_record->getLastSql();
                if($sms_info){
                    if(time() > $sms_info['expire_time'])exit(json_encode(array('error'=>'2','msg'=>'验证码已经失效！','dom_id'=>'phone')));
                }else {
                    exit(json_encode(array('error'=>'3','msg'=>'验证码错误！','dom_id'=>'phone')));
                }

                //手机号
                $now_phone = $database_user->field('`uid`')->field(true)->where($phone)->find();
                file_put_contents('phone.log',$database_user->getLastSql());
                if(!empty($now_phone)){
                    exit(json_encode(array('error'=>'4','msg'=>'手机号已经存在！','dom_id'=>'phone')));
                }
                
                $_POST['pwd'] = md5($_POST['reg_pwd']);
                $_POST['reg_ip'] = get_client_ip(1);
                $_POST['reg_time'] = $_SERVER['REQUEST_TIME'];
                $_POST['is_check_phone'] = 1;
                $_POST['add_time'] = time();
                $info = $database_user->add($_POST);
                if($info){
                    exit(json_encode(array('error'=>'0','msg'=>'注册成功请登录！','dom_id'=>'phone')));
                }  else {
                    exit(json_encode(array('error'=>'5','msg'=>'注册异常请重试！','dom_id'=>'phone')));
                }
            
            }
        }
        
        public  function sendCode(){
            $phone = I('phone', 0);
            $phone = trim($_POST['phone']);
            if (preg_match("/^1[0-9]{10}$/", $phone)) {
                if (! $phone) {
                    exit(json_encode(array('error'=>'4','msg'=>'手机号有误，请重新输入')));
                }
                $code = mt_rand(1000, 9999);
                $text = '您的验证码是：' . $code . '。此验证码20分钟内有效，请不要把验证码泄露给其他人。如非本人操作，可不用理会！';

    //              $_SESSION['sys-send-time']['now'] = time();
    //              $expire_time = $_SESSION['sys-send-time']['now'] + 1200;
                    $send_time = time();
                    $expire_time  = time() + 1200;

                $return = Sms::sendSms(array( 'content' => $text, 'mobile' => $phone, 'uid' => $_SESSION['user']['uid'], 'type' => 'domains_user',
                    'send_time'=>$send_time,'expire_time'=>$expire_time,'extra'=>$code));
                exit(json_encode(array('error'=>'0','msg'=>'获取验证码成功，请及时查看~','expire_time'=>$expire_time)));
            } else {
                exit(json_encode(array('error'=>'4','msg'=>'手机号有误，请重新输入')));
            }

            if (! $phone) {
                    $this->returnCode('20042001');
            }

	}
        
        
        public function login_check(){
            if($this->isAjax()){
                if($_POST['login_verify']){
                    if(md5($_POST['login_verify']) != $_SESSION['domain_reg_verify']){
                        exit(json_encode(array('error'=>'1','msg'=>'验证码不正确！','dom_id'=>'verify')));
                    }
                }
            $database_user = D('User');
			$account = trim($_POST['login_account']);
			if(preg_match('/^\d+$/',$account)){
				$condition_user['phone'] = $account;
			}else{
				$condition_user['email'] = $account;
			}
            $now_user = $database_user->field(true)->where($condition_user)->find();
            if(empty($now_user)){
                exit(json_encode(array('error'=>'2','msg'=>'用户名不存在！','dom_id'=>'account')));
            }
            $pwd = md5($_POST['login_pwd']);
            if($pwd != $now_user['pwd']){
                $_SESSION['login_error_count'] +=1;
                exit(json_encode(array('error'=>'3','msg'=>'密码错误！','dom_id'=>'pwd')));
            }
            if($now_user['status'] == 0){
                exit(json_encode(array('error'=>'4','msg'=>'您被禁止登录！请联系工作人员获得详细帮助。','dom_id'=>'login_account')));
            }else if($now_user['status'] == 2){
                exit(json_encode(array('error'=>'5','msg'=>'您的帐号正在审核中，请耐心等待或联系工作人员审核。','dom_id'=>'login_account')));
            }
//            elseif($now_user['is_check_email'] == 0){
//                exit(json_encode(array('error'=>'6','msg'=>"您的邮箱尚未验证，请您及时登录邮箱【 {$now_user['email']} 】确认注册邮件。",'dom_id'=>'account')));
//            }
            $data_user['uid'] = $now_user['uid'];
            $data_user['last_ip'] = get_client_ip(1);
            $data_user['last_time'] = $_SERVER['REQUEST_TIME'];

            $Db_loginlog = M('Loginlog');

            if($database_user->data($data_user)->save()){
				if(!empty($now_user['last_ip'])){
					import('ORG.Net.IpLocation');
					$IpLocation = new IpLocation();
					$last_location = $IpLocation->getlocation(long2ip($now_user['last_ip']));
					$now_user['last']['country'] = iconv('GBK','UTF-8',$last_location['country']);
					$now_user['last']['area'] = iconv('GBK','UTF-8',$last_location['area']);
				}
                $databases_user_group = M('User_group');
                $group_info = $databases_user_group->where(array('group_id'=>$now_user['group_id']))->find();
                $now_user['permissions'] = explode(',',$group_info['permissions_id']);
                session('user',$now_user);
                //登录日志
                $IpLocation = new IpLocation();
                $log_location = $IpLocation->getlocation(long2ip(get_client_ip(1)));
                $log_user['last']['country'] = iconv('GBK','UTF-8',$log_location['country']);
                $log_user['last']['area'] = iconv('GBK','UTF-8',$log_location['area']);
                $log_data['uid'] = $now_user['uid'];
                $log_data['log_ip'] = get_client_ip(1);
                $log_data['log_location'] =$log_user['last']['country'] . $log_user['last']['area'];
                $log_data['log_status'] = 1;
                $log_data['log_time'] = time();
                $Db_loginlog->data($log_data)->add();
                $_SESSION['login_error_count'] = '';
                exit(json_encode(array('error'=>'0','msg'=>'登录成功,现在跳转~','dom_id'=>'login_account')));
            }else{
                //登录日志失败
                exit(json_encode(array('error'=>'6','msg'=>'登录信息保存失败,请重试！','dom_id'=>'login_account')));
            }
        }else{
            exit('deney Access !');
        }
            
//            exit(json_encode(array('error'=>'3','msg'=>'123！','dom_id'=>'pwd')));
        }

	//手机验证码
	public function regcheck(){

		$this->display();
	}

	public function weixin(){
		$_SESSION['weixin']['referer'] = !empty($_GET['referer']) ? htmlspecialchars_decode($_GET['referer']) : U('Profile/index');
		$_SESSION['weixin']['state']   = md5(uniqid());
		
		$customeUrl = $this->config['site_url'].'/wap.php?c=Login&a=weixin_back';
		$oauthUrl='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->config['wechat_appid'].'&redirect_uri='.urlencode($customeUrl).'&response_type=code&scope=snsapi_userinfo&state='.$_SESSION['weixin']['state'].'#wechat_redirect';
		redirect($oauthUrl);
	}
	
	public function weixin_back(){
		$referer = !empty($_SESSION['weixin']['referer']) ? $_SESSION['weixin']['referer'] : U('Profile/index');

		// if (isset($_GET['code']) && isset($_GET['state']) && ($_GET['state'] == $_SESSION['weixin']['state'])){
		if (isset($_GET['code'])){
			unset($_SESSION['weixin']['state']);
			import('ORG.Net.Http');
			$http = new Http();
			$return = $http->curlGet('https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->config['wechat_appid'].'&secret='.$this->config['wechat_appsecret'].'&code='.$_GET['code'].'&grant_type=authorization_code');
			$jsonrt = json_decode($return,true);
			if($jsonrt['errcode']){
				$error_msg_class = new GetErrorMsg();
				$this->error_tips('授权发生错误：'.$error_msg_class->wx_error_msg($jsonrt['errcode']),U('Login/index'));
			}
			
			$return = $http->curlGet('https://api.weixin.qq.com/sns/userinfo?access_token='.$jsonrt['access_token'].'&openid='.$jsonrt['openid'].'&lang=zh_CN');
			$jsonrt = json_decode($return,true);
			if ($jsonrt['errcode']) {
				$error_msg_class = new GetErrorMsg();
				$this->error_tips('授权发生错误：'.$error_msg_class->wx_error_msg($jsonrt['errcode']),U('Login/index'));
			}
			
			if(!empty($this->user_session)){
				$data_user = array(
					'union_id' 	=> ($jsonrt['unionid'] ? $jsonrt['unionid'] : ''),
					'sex' 		=> $jsonrt['sex'],
					'province' 	=> $jsonrt['province'],
					'city' 		=> $jsonrt['city'],
					'avatar' 	=> $jsonrt['headimgurl'],
					'last_weixin_time' 	=> $_SERVER['REQUEST_TIME'],
				);
				D('User')->where(array('uid'=>$this->user_session['uid']))->data($data_user)->save();
				redirect($referer);
			}else{
				//优先使用 unionid 登录
				/*
				if(!empty($jsonrt['unionid'])){
					$this->autologin('union_id',$jsonrt['unionid'],$referer);
				}else{
					//再次使用 openid 登录
					$this->autologin('openid',$jsonrt['openid'],$referer);
				}
				*/
				//使用 openid 登录
				$this->autologin('openid',$jsonrt['openid'],$referer);
				
				
				/*注册用户*/
				$data_user = array(
					'openid' 	=> $jsonrt['openid'],
					'union_id' 	=> ($jsonrt['unionid'] ? $jsonrt['unionid'] : ''),
					'nickname' 	=> $jsonrt['nickname'],
					'sex' 		=> $jsonrt['sex'],
					'province' 	=> $jsonrt['province'],
					'city' 		=> $jsonrt['city'],
					'avatar' 	=> $jsonrt['headimgurl'],
				);

				$_SESSION['weixin']['user'] = $data_user;
				$this->assign('referer',$referer);
				if($this->config['weixin_login_bind']){
					$this->display();
				}else{
					redirect(U('Login/weixin_nobind'));
				} 
			}
		}else{
			$this->error_tips('访问异常！请重新登录。',U('Login/index',array('referer'=>urlencode($referer))));
		}
	}
	public function weixin_bind(){
		if(empty($_SESSION['weixin']['user'])){
			//$this->error('微信授权失效，请重新登录！');
			exit(json_encode(array('error'=>1,'msg'=>'微信授权失效，请重新登录')));
		}
		$login_result = D('User')->checkin($_POST['phone'],$_POST['password']);
		if($login_result['error_code']){
			$this->error($login_result['msg']);
		}else{
			$now_user = $login_result['user'];
			$condition_user['uid'] = $now_user['uid'];
			$data_user['openid'] = $_SESSION['weixin']['user']['openid'];
			if($_SESSION['weixin']['user']['union_id']){
				$data_user['union_id'] 	= $_SESSION['weixin']['user']['union_id'];
			}
			if(empty($now_user['avatar'])){
				$data_user['avatar'] 	= $_SESSION['weixin']['user']['avatar'];
			}
			if(empty($now_user['sex'])){
				$data_user['sex']		= $_SESSION['weixin']['user']['sex'];
			}
			if(empty($now_user['province'])){
				$data_user['province'] 	= $_SESSION['weixin']['user']['province'];
			}
			if(empty($now_user['city'])){
				$data_user['city'] 		= $_SESSION['weixin']['user']['city'];
			}
			/****判断此用户是否在user_import表中***/
			$user_importDb=D('User_import');
			$user_import=$user_importDb->where(array('telphone'=>$condition_user['phone']))->find();
			if(!empty($user_import)){
			 if($user_import['isuse']==0){
			   $data_user['truename']=$user_import['ppname'];
			   $data_user['qq']=$user_import['qq'];
			   $data_user['email']=$user_import['email'];
			   $data_user['level']=$user_import['level'];
			   $data_user['score_count']=$user_import['integral'];
			   $data_user['now_money']=$user_import['money'];
			   $data_user['importid']=$user_import['id'];
 			   $data_user['youaddress'] = !empty($user_import['address']) ? str_replace('|', ' ', $user_import['address']) : '';
			 }
			  $data_user['status'] = 2; /*                 * *未审核*** */
			   $mer_id=$user_import['mer_id'];
			   if($mer_id>0){
			      $merchant_user_relationDb=M('Merchant_user_relation');
				  $mwhere=array('openid'=>$data_user['openid'],'mer_id'=>$mer_id);
				  $mtmp=$merchant_user_relationDb->where($mwhere)->find();
				  if(empty($mtmp)){
					 $mwhere['dateline']=time();
					 $mwhere['from_merchant']=3;
				     $merchant_user_relationDb->add($mwhere);
				  }
			   }
			}
			if(D('User')->where($condition_user)->data($data_user)->save()){
				unset($_SESSION['weixin']);
				session('user',$now_user);
				setcookie('login_name',$now_user['phone'],$_SERVER['REQUEST_TIME']+10000000,'/');
				if(!empty($user_import)){
				   $user_importDb->where(array('id'=>$user_import['id']))->save(array('isuse'=>1));
				}
				//$this->success('绑定成功！');
				exit(json_encode(array('error'=>0,'msg'=>'绑定成功')));
			}else{
				//$this->error('绑定失败！请重试。');
				exit(json_encode(array('error'=>1,'msg'=>'绑定失败！请重试')));
			}
		}
	}
	
	protected function autologin($field, $value, $referer) {
        $result = D('User')->autologin($field, $value);
        if (empty($result['error_code'])) {
            $now_user = $result['user'];
            session('user', $now_user);
			/*$this->assign('errorcheck',1);
			$this->assign('referer',$referer);
			$this->assign('msg','登录成功！');exit;*/
			// exit(json_encode(array('errorcheck'=>1,'msg'=>'登录成功！')));
			redirect(U('Profile/index'));
			$referer = U('Profile/index');
            $this->success('登录成功！', $referer);
            exit;
        } else if ($result['error_code'] && $result['error_code'] != 1001) {
            $this->error($result['msg'], U('Login/weixin'));
        }
    }
	
	public function weixin_bind_reg(){
		if(IS_POST){
			if(empty($_SESSION['weixin']['user'])){
				$this->error('微信授权失效，请重新登录！');
			}
		
			$condition_user['phone'] = $data_user['phone'] = trim($_POST['phone']);
			
			$database_user = D('User');
			if($database_user->field('`uid`')->where($condition_user)->find()){
				$this->error('手机号已存在');
			}
			
			if(empty($data_user['phone'])){
				$this->error('请输入手机号');
			}else if(empty($_POST['password'])){
				$this->error('请输入密码');
			}
			
			if(!preg_match('/^[0-9]{11}$/',$data_user['phone'])){
				$this->error('请输入有效的手机号');
			}

			$data_user['pwd'] = md5($_POST['password']);
			
			$data_user['add_time'] = $data_user['last_time'] = $_SERVER['REQUEST_TIME'];
			$data_user['add_ip'] = $data_user['last_ip'] = get_client_ip(1);
			
			
			$data_user['nickname'] = $_SESSION['weixin']['user']['nickname'];
			$data_user['openid'] = $_SESSION['weixin']['user']['openid'];
			if($_SESSION['weixin']['user']['union_id']){
				$data_user['union_id'] 	= $_SESSION['weixin']['user']['union_id'];
			}
			$data_user['avatar'] 	= $_SESSION['weixin']['user']['avatar'];
			$data_user['sex']		= $_SESSION['weixin']['user']['sex'];
			$data_user['province'] 	= $_SESSION['weixin']['user']['province'];
			$data_user['city'] 		= $_SESSION['weixin']['user']['city'];
			
			if ($this->config['register_give_money_condition'] == 2 || $this->config['register_give_money_condition'] == 3) {
				$data_user['now_money'] = $this->config['register_give_money'];
			}
			
			/****判断此用户是否在user_import表中***/
			$user_importDb=D('User_import');
			$user_import=$user_importDb->where(array('telphone'=>$condition_user['phone'],'isuse'=>'0'))->find();
			if(!empty($user_import)){
			   $data_user['truename']=$user_import['ppname'];
			   $data_user['qq']=$user_import['qq'];
			   $data_user['email']=$user_import['email'];
			   $data_user['level']=$user_import['level'];
			   $data_user['score_count']=$user_import['integral'];
			   $data_user['now_money']=$user_import['money'] ? $user_import['money'] : 0;;
			   $data_user['importid']=$user_import['id'];
			   $data_user['youaddress'] = !empty($user_import['address']) ? str_replace('|', ' ', $user_import['address']) : '';
			   $data_user['status'] = 2;
			   $mer_id=$user_import['mer_id'];
			   if($mer_id>0){
			      $merchant_user_relationDb=M('Merchant_user_relation');
				  $mwhere=array('openid'=>$data_user['openid'],'mer_id'=>$mer_id);
				  $mtmp=$merchant_user_relationDb->where($mwhere)->find();
				  if(empty($mtmp)){
					 $mwhere['dateline']=time();
					 $mwhere['from_merchant']=3;
				     $merchant_user_relationDb->add($mwhere);
				  }
			   }
			}
			if($uid = $database_user->data($data_user)->add()){
				$session['uid'] = $uid;
				$session['phone'] = $data_user['phone'];
				session('user',$session);
				
				setcookie('login_name',$session['phone'],$_SERVER['REQUEST_TIME']+1000000,'/');
				if(!empty($user_import)){
				   $user_importDb->where(array('id'=>$user_import['id']))->save(array('isuse'=>1));
				}
				redirect(U('Profile/index'));
				//$this->success('注册成功');
			}else{
				$this->error('注册失败！请重试。');
			}
		}
	}
	public function weixin_nobind(){
		if(empty($_SESSION['weixin']['user'])){
			$this->error('微信授权失效，请重新登录！');
		}
		$reg_result = D('User')->autoreg($_SESSION['weixin']['user']);
		if($reg_result['error_code']){
			$this->error_tips($reg_result['msg']);
		}else{	
			$login_result = D('User')->autologin('openid',$_SESSION['weixin']['user']['openid']);
			if($login_result['error_code']){
				$this->error_tips($login_result['msg'],U('Login/index'));
			}else{
				$now_user = $login_result['user'];
				session('user',$now_user);
				//$referer = !empty($_SESSION['weixin']['referer']) ? $_SESSION['weixin']['referer'] : U('Profile/index');
				$referer = U('Profile/index');
				unset($_SESSION['weixin']);
				redirect($referer);
				exit;
			}
		}
	}
	
	//密码设置
	public function setpwd(){

		$this->display();
	}
        
        public function verify(){
            $verify_type = $_GET['type'];
            if(empty($verify_type)){exit;}
            import('ORG.Util.Image');
            Image::buildImageVerify(4,1,'jpeg',53,26,'domain_'.$verify_type.'_verify');
        }

    //密码找回
    public function forget(){
        $this->display();
    }
    
    public function forget_check(){
        if($this->isAjax()){
            $databases_sms_record = M('Sms_record');
            $database_user = M('User');
            $phone['phone'] =trim($_POST['phone']);

            $sms_info = $databases_sms_record->where(array('phone'=>$_POST['phone'],'extra'=>$_POST['extra']))->order('pigcms_id desc')->find();
    //            echo $databases_sms_record->getLastSql();
            if($sms_info){
                if(time() > $sms_info['expire_time'])exit(json_encode(array('error'=>'2','msg'=>'验证码错误！','dom_id'=>'phone')));
            }else {
                exit(json_encode(array('error'=>'3','msg'=>'验证码错误！','dom_id'=>'phone')));
            }
            //手机号
            $user_uid = $database_user->field('`uid`')->where($phone)->find();
            if(empty($user_uid)){
                exit(json_encode(array('error'=>'4','msg'=>'手机号不存在！','dom_id'=>'phone')));
            }

            $forget_pwd['pwd'] = md5($_POST['forget_pwd']);
            $info = $database_user->where(array('uid'=>$user_uid['uid']))->save($forget_pwd);
            if($info){
                exit(json_encode(array('error'=>'0','msg'=>'修改成功请登录！','dom_id'=>'phone')));
            }  else {
                exit(json_encode(array('error'=>'5','msg'=>'修改异常请重试！','dom_id'=>'phone')));
            }
        }
    }
}